import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

import '../utils/api.dart';
import '../utils/logger.dart';
import '../widgets/tags/empty.dart';
import '../application.dart';
import 'home/home.dart' show HomePage;
import 'channel/index.dart' as channel;
import 'member/index.dart' as member;

class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  int _lastTapBack = 0;
  int _selectedIndex = 0;
  late final PageController _controller =
      PageController(initialPage: _selectedIndex);

  bool initialized = false;
  bool isError = false;
  bool isReload = false;

  @override
  initState() {
    super.initState();
    _init();
  }

  @override
  dispose() {
    _controller.dispose();
    super.dispose();
  }

  _init() async {
    try {
      await app.login.restoreToken();
      await app.getSiteinfo();
      setState(() {
        initialized = true;
      });
    } on ServerException catch (_) {
      setState(() {
        isError = true;
      });
    }
  }

  void _onItemTapped(index) {
    if (index == 2) {
      int curPage = _controller.page?.round() ?? 0;
      setState(() {
        _selectedIndex = curPage > 1 ? (curPage + 1) : curPage;
      });
      app.route('/feedback');
    } else {
      index = index > 1 ? (index - 1) : index;
      setState(() {
        _selectedIndex = index;
        _controller.animateToPage(
          _selectedIndex,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeIn,
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!initialized) {
      return AnimatedSwitcher(
        duration: const Duration(milliseconds: 300),
        child: isError ? renderError() : renderLoading(),
      );
    }

    return WillPopScope(
      onWillPop: () {
        int now = DateTime.now().millisecondsSinceEpoch;
        logger.info('onWillPop $_lastTapBack $now');
        if (now - _lastTapBack > 800) {
          _lastTapBack = now;
          MyDialog.toast(
            '再次点击返回退出应用',
            duration: const Duration(seconds: 1),
            style: MyDialog.theme.toastStyle?.bottom(),
          );
          return Future.value(false);
        } else {
          return Future.value(true);
        }
      },
      child: Scaffold(
        body: PageView(
          controller: _controller,
          onPageChanged: (index) {
            setState(() {
              _selectedIndex = index > 1 ? (index + 1) : index;
            });
          },
          children: const [
            HomePage(),
            channel.IndexPage(channel: 'blog'),
            channel.IndexPage(channel: 'works'),
            member.IndexPage(),
          ],
        ),
        bottomNavigationBar: BottomAppBar(
          shape: const CircularNotchedRectangle(),
          elevation: 16,
          child: BottomNavigationBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            items: const [
              BottomNavigationBarItem(
                icon: Icon(CupertinoIcons.house),
                activeIcon: Icon(CupertinoIcons.house_fill),
                label: '首页',
              ),
              BottomNavigationBarItem(
                icon: Icon(CupertinoIcons.doc_text),
                activeIcon: Icon(CupertinoIcons.doc_text_fill),
                label: '日志',
              ),
              BottomNavigationBarItem(icon: SizedBox(), label: ''),
              BottomNavigationBarItem(
                icon: Icon(CupertinoIcons.collections),
                activeIcon: Icon(CupertinoIcons.collections_solid),
                label: '作品',
              ),
              BottomNavigationBarItem(
                icon: Icon(CupertinoIcons.person_alt_circle),
                activeIcon: Icon(CupertinoIcons.person_alt_circle_fill),
                label: '会员',
              ),
            ],
            currentIndex: _selectedIndex,
            //selectedItemColor: Colors.blue,
            onTap: _onItemTapped,
            type: BottomNavigationBarType.fixed,
            //unselectedItemColor: Colors.grey,
            selectedFontSize: 12,
            unselectedFontSize: 12,
            showUnselectedLabels: true,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            app.route('/feedback');
          },
          heroTag: 'feedback-page',
          child: const Icon(CupertinoIcons.paperplane),
        ),
        floatingActionButtonLocation:
            FloatingActionButtonLocation.miniCenterDocked,
      ),
    );
  }

  Widget renderError() {
    return InkWell(
      onTap: () {
        setState(() {
          initialized = false;
          isError = false;
          isReload = true;
        });
        _init();
      },
      child: const Center(
        child: TagEmpty(
          '网络连接错误,点击重试',
          icon: Icons.wifi_off,
        ),
      ),
    );
  }

  Widget renderLoading() {
    return Container(
      color: Colors.white,
      child: const Center(
        child: CircularProgressIndicator(),
      ),
    );
  }
}
